<template>
  <div class="search-suggestion">
    <van-cell
    v-for="(item,index) in suggestionList"
    :key="index"
    icon="search"
    @click="$emit('search', item)"
    >
        <span slot="title" v-html="highlight(item,searchText)"></span>
    </van-cell>
  </div>
</template>

<script>
import { getSuggestion } from '@/api/search'
import { debounce } from 'lodash'
export default {
  name: 'SearchSuggestion',
  components: {},
  props: {
    searchText: {
      type: String,
      required: true
    }
  },
  data () {
    return {
      // 接收联想搜索结果的数组
      suggestionList: []
    }
  },
  computed: {},
  watch: {
    // searchText (val) {
    //   console.log(val)
    // }
    searchText: {
      handler (val) {
        this.loadSuggestion(val)
      },
      immediate: true
    }
  },
  created () {},
  mounted () {},
  methods: {
    loadSuggestion: debounce(
      async function (val) {
        try {
          const { data } = await getSuggestion(val)
          this.suggestionList = data.data.options
        } catch (err) {

        }
      }, 500
    ),
    // 参数 source: 原始字符串
    // 参数 keyword: 需要高亮的关键词
    // 返回值：替换之后的高亮字符串
    highlight (source, keyword) {
      const reg = new RegExp(keyword, 'gi')
      return source.replace(reg, `<span style="color: #3296fa">${keyword}</span>`)
    }
  }
}
</script>

<style scoped lang="less"></style>
